package maa.action.admin.user;

import maa.action.Action;
import maa.action.ActionResult;
import maa.dao.h2.UserDAOimpl;
import maa.dao.DAOCommand;
import maa.dao.DAOFactory;
import maa.dao.DAOManager;
import maa.database.ConnectionPool;
import maa.entity.Gender;
import maa.entity.Role;
import maa.entity.User;
import maa.action.ActionException;
import maa.dao.DAOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Date;

public class AddUser implements Action {
    @Override
    public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        final User user = new User();
        HttpSession session = req.getSession();
        ActionResult actionResult = new ActionResult();
        user.setPassword(req.getParameter("password"));
        user.setName(req.getParameter("name"));
        user.setEmail(req.getParameter("email"));
        user.setSurname(req.getParameter("surname"));
        user.setBirthdate(Date.valueOf(req.getParameter("birthdate")));
        user.setGender(Gender.valueOf(req.getParameter("gender").toUpperCase()));
        user.setRole(Role.CLIENT);
        String password = req.getParameter("password");
        String repeatedPassword = req.getParameter("password_check");
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        DAOCommand command = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                try {
                    UserDAOimpl userDAO = daoManager.getUserDAO();
                    return userDAO.create(user);
                } catch (DAOException e) {
                    throw new ActionException("Exception in userDAO.create(user)");
                }
            }
        };

        Boolean flag = (Boolean) daoManager.executeAndClose(command);

        if (password.equals(repeatedPassword)) {
            if (flag) {
                actionResult.setResult("admin-cabinet");
                actionResult.setRedirected(true);
            }
        } else {
            actionResult.setResult("main");
            actionResult.setRedirected(false);
        }

        return actionResult;
    }
}
